package com.ihighest.app.infox.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.json.JSONException;

import com.ihighest.app.common.api.Api;
import com.ihighest.app.common.api.ApiCallback;
import com.ihighest.app.common.api.ApiParam;
import com.ihighest.app.common.api.ApiResult;
import com.ihighest.app.common.kit.SharedPreferencesKit;
import com.ihighest.app.common.kit.ToastKit;
import com.ihighest.app.infox.Const;
import com.ihighest.app.infox.R;
import com.ihighest.app.infox.activity.ApplyBeSpecialist.TimeCount;
import com.ihighest.app.infox.myview.ActivityTitle;
import com.ihighest.app.infox.myview.ImgSecondTextView;
import com.ihighest.app.infox.tools.RegexKit;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 开通专栏
 * 
 * @author lkx Created at 2015-10-13 下午8:01:46
 * @version 1.0
 */
public class ApplyForColumnActivity extends BaseActivity implements OnClickListener, OnCheckedChangeListener {
	private ActivityTitle title;
	private EditText trueName, phoneNumber, weiXinNumber, qqNumber, verificationCode, email, idCard, memo, columnName;
	private RadioButton male, female;
	private TextView columnLable, address, getCode;
	private ImageView cardPositive, cardnNegative, columnLogo;
	private EditText authorText;
	private Bitmap myBitmap;
	private static final String PHOTO_FILE_NAME = "card.jpg";
	private File tempFile;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private int image;// 选中的是正面还是反面的标识，0表示正面，1标识反面
	private ApiParam param;
	File fTemp1 = null;// 正面临时文件
	File fTemp2 = null;// 反面临时文件
	private String gender;
	private int time;// 倒计时时间
	private TimeCount timer;
	private String codeId;
	private File logoImg;
	private boolean isEmail = true;
	private Uri photoUri;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.infox_activity_applyfor_column);
		initView();
	}

	/**
	 * 初始化绑定
	 * 
	 * @author lkx Created at 2015-10-13 下午7:57:10
	 */
	private void initView() {
		tempFile = new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME);
		param = ApiParam.create();
		title = (ActivityTitle) findViewById(R.id.applyForColumnActivityTitle);
		title.setTitle("开通专栏");
		title.setViewVersible(title.titleBack, title.rightText);
		title.setViewGone(title.titleMsg, title.titleRefresh);
		title.setRightTextViewText("提交");
		trueName = (EditText) findViewById(R.id.applyForColumnTruenName);
		phoneNumber = (EditText) findViewById(R.id.applyForColumnphoneNumber);
		weiXinNumber = (EditText) findViewById(R.id.applyForColumnWeixin);
		qqNumber = (EditText) findViewById(R.id.applyForColumnQQ);
		email = (EditText) findViewById(R.id.applyForColumnEmail);
		idCard = (EditText) findViewById(R.id.applyForColumnCardNumber);
		memo = (EditText) findViewById(R.id.inputColumnAbstract);
		columnName = (EditText) findViewById(R.id.applyForColumnName);
		verificationCode = (EditText) findViewById(R.id.columnVerificationCode);
		address = (TextView) findViewById(R.id.applyForColumnAddress);
		getCode = (TextView) findViewById(R.id.getCode);
		columnLogo = (ImageView) findViewById(R.id.columnLogo);
		male = (RadioButton) findViewById(R.id.rbMale);
		female = (RadioButton) findViewById(R.id.rbFemale);
		cardPositive = (ImageView) findViewById(R.id.applyForColumncardImgFrontage);
		cardPositive.setOnClickListener(this);
		cardnNegative = (ImageView) findViewById(R.id.applyForColumncardImgBack);
		authorText = (EditText) findViewById(R.id.inputAutherAbstract);
		columnLogo.setOnClickListener(this);
		cardnNegative.setOnClickListener(this);
		male.setOnCheckedChangeListener(this);
		female.setOnCheckedChangeListener(this);
		// 默认选中男
		gender = "m";
		male.setChecked(true);
		param.addParam("sex", gender);
		title.rightText.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				judgeData();
			}
		});
		findViewById(R.id.getCode).setOnClickListener(this);
	}

	/**
	 * 数据检验
	 * 
	 * @author lkx Created at 2015-11-18 下午2:34:59
	 */
	protected void judgeData() {

		if (TextUtils.isEmpty(trueName.getText().toString()) || TextUtils.isEmpty(phoneNumber.getText().toString())
				|| TextUtils.isEmpty(idCard.getText().toString()) || TextUtils.isEmpty(columnName.getText().toString())
				|| TextUtils.isEmpty(verificationCode.getText().toString())) {
			ToastKit.showShort(ApplyForColumnActivity.this, "请您完善所有必填项信息");

		} else {
			if (fTemp1 == null) {
				ToastKit.showShort(ApplyForColumnActivity.this, "请选择身份证正面照片");
			} else if (fTemp2 == null) {
				ToastKit.showShort(ApplyForColumnActivity.this, "请选择身份证反面照片");
			} else if (TextUtils.isEmpty(memo.getText().toString())) {
				ToastKit.showShort(ApplyForColumnActivity.this, "请输入简介信息");
			} else {
				// if
				// (!RegexKit.personIdValidation(idCard.getText().toString())) {
				// ToastKit.showShort(ApplyForColumnActivity.this,
				// "请输入正确的身份证号");
				// } else {
				commitData();
				// }
			}
		}

	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.applyForColumncardImgBack:
			image = 1;
			chooseImg();
			break;

		case R.id.applyForColumncardImgFrontage:
			image = 0;
			chooseImg();
			break;
		case R.id.columnLogo:
			image = 3;
			chooseImg();
			break;
		case R.id.getCode:
			if (TextUtils.isEmpty(phoneNumber.getText().toString())) {
				ToastKit.showShort(ApplyForColumnActivity.this, "请输入手机号");
			} else if (!RegexKit.isMobile(phoneNumber.getText().toString())) {
				ToastKit.showShort(ApplyForColumnActivity.this, "请输入正确手机号");
			} else
				Api.post("mobilecaptcha",
						ApiParam.create().addParam("phone", phoneNumber.getText().toString()).addParam("type", "columnist"),
						new ApiCallback(this) {

							private long countTime;

							@Override
							public void handleSuccess(ApiResult result) {
								try {
									if (result.getCode() == 100) {
										codeId = result.getData().getString("captcha_id");
										time = Integer.valueOf(result.getData().getString("time"));
										countTime = time * 1000;

										getCode.setClickable(false);
										getCode.setBackgroundResource(R.drawable.infox_register_btn_gettextcode_bg);
									} else {
										ToastKit.showShort(ApplyForColumnActivity.this, TextUtils.isEmpty(result.getMsg()) ? "获取验证码失败"
												: result.getMsg());
									}
								} catch (JSONException e) {
									Log.e(TAG, e.getMessage(), e);
								}
								timer = new TimeCount(countTime, 1000);
								timer.start();
							}

							@Override
							public void handleFailure(Exception e, String msg) {
							}
						}, this);
			break;
		}

	}

	@Override
	public void onCheckedChanged(CompoundButton rb, boolean ischeck) {
		if (ischeck) {
			switch (rb.getId()) {
			case R.id.rbMale:
				gender = "m";
				break;

			case R.id.rbFemale:
				gender = "f";
				break;
			}
		}

	}

	/**
	 * 选择图片
	 * 
	 * @author lkx Created at 2015-11-18 上午10:32:26
	 */
	private void chooseImg() {
		new AlertDialog.Builder(this).setTitle("选择图片获取方式").setNegativeButton("相册", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();

				// 激活系统图库，选择一张图片
				Intent intent = new Intent(Intent.ACTION_PICK);
				intent.setType("image/*");
				startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

			}
		}).setPositiveButton("拍照", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int whichButton) {

				Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
				// 判断存储卡是否可以用，可用进行存储
				if (hasSdcard()) {
					ContentValues values = new ContentValues();
					photoUri = ApplyForColumnActivity.this.getContentResolver()
							.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
					intent.putExtra(MediaStore.EXTRA_OUTPUT,
							Uri.fromFile(new File(Environment.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
				}
				startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
			}
		}).show();
	}

	/**
	 * 是否存在sd卡
	 * 
	 * @return
	 * @author lkx Created at 2015-10-17 上午10:53:34
	 */
	private boolean hasSdcard() {
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 提交数据
	 * 
	 * @author lkx Created at 2015-11-18 上午10:14:15
	 */
	private void commitData() {
		title.rightText.setClickable(false);
		param.addParam("title", trueName.getText().toString());
		param.addParam("sex", gender);
		param.addParam("phone", phoneNumber.getText().toString());
		param.addParam("idcard", idCard.getText().toString());
		param.addParam("memo", memo.getText().toString());
		param.addParam("name", columnName.getText().toString());
		param.addParam("captcha", verificationCode.getText().toString());
		param.addParam("captcha_id", codeId);
		if (!TextUtils.isEmpty(weiXinNumber.getText().toString()))
			param.addParam("wechat", weiXinNumber.getText().toString());
		if (!TextUtils.isEmpty(address.getText().toString()))
			param.addParam("addr", address.getText().toString());
		if (!TextUtils.isEmpty(qqNumber.getText().toString()))
			param.addParam("qq", qqNumber.getText().toString());
		if (!TextUtils.isEmpty(email.getText().toString())) {
			if (RegexKit.isEmail(email.getText().toString())) {
				param.addParam("mail", email.getText().toString());
				isEmail = true;
			} else {
				ToastKit.showShort(ApplyForColumnActivity.this, "请输入正确的邮箱");
				isEmail = false;
			}
		}

		if (!TextUtils.isEmpty(authorText.getText().toString())) {
			param.addParam("writerMemo", authorText.getText().toString());
		}
		if (isEmail) {

			Api.post("apply/columnist", param, new ApiCallback(ApplyForColumnActivity.this) {

				@Override
				public void handleSuccess(ApiResult result) {
					if (result.getCode() == 100) {
						finish();
					} else {
						ToastKit.showShort(ApplyForColumnActivity.this, result.getMsg());
					}

				}

				@Override
				public void handleFailure(Exception e, String msg) {
					// TODO Auto-generated method stub
					title.rightText.setClickable(true);
				}
			}, ApplyForColumnActivity.this);
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径

				Uri uri = data.getData();
				crop(uri);
			}

		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (hasSdcard()) {
				if (tempFile != null) {
					crop(Uri.fromFile(tempFile));
				}

			} else {
				Toast.makeText(ApplyForColumnActivity.this, "未找到存储卡，无法存储照片！", 0).show();
			}

		} else if (requestCode == PHOTO_REQUEST_CUT) {
			try {
				myBitmap = data.getParcelableExtra("data");
				if (image == 0) {
					this.cardPositive.setImageBitmap(myBitmap);
				}
				if (image == 1) {
					this.cardnNegative.setImageBitmap(myBitmap);
				}
				if (image == 3) {
					this.columnLogo.setImageBitmap(myBitmap);
				}
				bitMapToFile();
				boolean delete = tempFile.delete();

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 图片裁剪
	 * 
	 * @param uri
	 * @author lkx Created at 2015-10-17 上午10:58:44
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);
		// 图片格式
		intent.putExtra("outputFormat", "JPEG");
		intent.putExtra("noFaceDetection", true);// 取消人脸识别
		intent.putExtra("return-data", true);// true:不返回uri，false：返回uri
		startActivityForResult(intent, PHOTO_REQUEST_CUT);
	}

	/**
	 * 图片转换为file文件
	 * 
	 * @author lkx Created at 2015-11-17 上午9:57:45
	 */
	private void bitMapToFile() {
		if (myBitmap != null) {
			BufferedOutputStream bos = null;

			try {
				if (image == 0) {// 正面证件照
					fTemp1 = File.createTempFile("card", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp1));
				}
				if (image == 1) {// 反面证件照
					fTemp2 = File.createTempFile("card2", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(fTemp2));
				}
				if (image == 3) {
					logoImg = File.createTempFile("logo", ".jpg");
					bos = new BufferedOutputStream(new FileOutputStream(logoImg));
				}
				// fTemp = File.createTempFile("card", ".jpg");

				// BufferedOutputStream bos = new BufferedOutputStream(new
				// FileOutputStream(fTemp));
				myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
				bos.flush();
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (image == 0) {// 正面证件照
				param.addParam("pic1", fTemp1);
			}
			if (image == 1) {// 反面证件照
				param.addParam("pic2", fTemp2);
			}
			if (image == 3) {// 企业logo
				param.addParam("logo", logoImg);
			}
		}

	}

	/**
	 * 倒计时
	 * 
	 * @author lkx Created at 2015-11-18 下午2:55:16
	 * @version 1.0
	 */
	class TimeCount extends CountDownTimer {
		public TimeCount(long millisInFuture, long countDownInterval) {
			super(millisInFuture, countDownInterval);// 参数依次为总时长,和计时的时间间隔
		}

		@Override
		public void onFinish() {// 计时完毕时触发
			getCode.setBackgroundResource(R.drawable.infox_content_comment_bg);
			getCode.setText("重新获取");
			getCode.setClickable(true);

		}

		@Override
		public void onTick(long millisUntilFinished) {// 计时过程显示
			getCode.setClickable(false);
			getCode.setText((millisUntilFinished / 1000) + "s后重新获取");

		}
	}
}
